//Grunt的入口文件
//用于定义一些需要Grunt自动执行的任务
//需要导出一个函数，接收一个grunt的参数
/**
 * yarn add grunt-contrib-clean
 * 自动清除临时文件
 */
const sass = require("sass")
const loadGruntTasks = require("load-grunt-tasks")
const browserSync = require("browser-sync")
const useref = require("useref")
const fs = require("fs");
const bs = browserSync.create()
const pkg = require("./package.json");

module.exports = grunt => {
    grunt.initConfig({
        //sass转化为css功能
        sass: {
            options: {
                sourceMap: true, //设置后会生成相应的sourceMap文件
                implementation: sass
            },
            main: {
                files: {
                      // 目标文件：源文件
                    'dist/assets/styles/main.css': 'src/assets/styles/main.scss'
                }
            }
        },
        //js转化功能
        babel: {
            options: {
                sourceMap: true,//设置后会生成相应的sourceMap文件
                presets: ["@babel/preset-env"]
            },
            main: {
                files: {
                    // 目标文件：源文件
                    'dist/assets/scripts/main.js': 'src/assets/scripts/main.js'
                }
            }
        },
        web_swig: {
            options: {
                swigOptions: {
                    //缓存设置为false
                    cache: false
                },
                getData: function (tpl) {
                    //模板文件的数据
                    return pkg;
                }
            },
            main: {
                expand: true,
                cwd: 'src/',//源文件文件夹
                src: "**/*.html",//后缀名匹配
                dest: "dist/"//目标文件夹
            },
        },
        //监视功能
        watch: {
            js: {
                //文件地址
                files: ['src/assets/scripts/*.js'],
                //执行的任务
                tasks: ['babel']
            },
            css: {
                //文件地址
                files: ['src/assets/styles/*.scss'],
                //执行的任务
                tasks: ['sass']
            },
            html: {
                //文件地址
                files: ['src/*.html'],
                //执行的任务
                tasks: ['web_swig', 'bs-reload']
            }
        },
        //清除功能
        clean: {
            //所要清除的文件路径
            files: 'dist/**'
        }
    })

    // grunt.loadNpmTasks('grunt-sass')
    loadGruntTasks(grunt) //自动加载所有的grunt插件
    grunt.registerTask("useref", function () {
        const done = this.async()
        const cwd = 'dist/'
        const htmls = ['index.html', 'about.html', 'layouts/basic.html', 'partials/header.html', 'partials/footer.html']
        htmls.forEach((html, index) => {
          const inputHtml = fs.readFileSync(cwd + html, "utf8")
          const [code, result] = useref(inputHtml)
          for (let type in result) {
            const dests = Object.keys(result[type])
            dests.forEach(dest => {
              const src = result[type][dest].assets
              let read
              const files = src.map(file => {
                read = cwd + file
                if(file[0] === '/') {
                  read = file.substr(1)
                }
                return fs.readFileSync(read)
              })
              fs.writeFile(cwd + dest, files.join(''), (err) => {
                if (err) {
                    return console.error(err);
                }
                console.log(`${cwd + dest}数据写入${read}成功！`);
              })
            })
          }
          fs.writeFile(cwd + html, code, (err) => {
            if (err) {
              return console.error(err);
            }
            console.log(`${cwd + html}重写成功！`);
            if(index === htmls.length - 1) {
              done()
            }
          })
        })
    });
    grunt.registerTask('default', ['clean', 'sass', 'babel','watch'])
    grunt.registerTask('bs-reload', bs.reload)
    grunt.registerTask('bs', function () {
        const done = this.async()
        bs.init({
            server: {
                port: 8080,
                // baseDir: 'dist',
                baseDir: ["dist", "public", "src"],
                files: 'dist/**',
                // open:false,
                routes: {
                    '/node_modules': "node_modules"
                }
            }
        })
    })
    grunt.registerTask('compile', ['clean', 'sass', 'babel', 'web_swig', 'useref']);
}